<?php

require_once( FRAMEWORK_PATH . 'lib/utils.php');
require_once( FRAMEWORK_PATH . 'models/profile.php');

class Wall{

	/**
	 * The registry object
	 */
	private $registry;

	/**
	 * Statuses ID
	 */
	private $id;

	/**
	 * Poster of the status update / profile message
	 */
	private $poster;

	/**
	 * The profile the status update / profile message was posed on
	 */
	private $profile;

	/**
	 * Type of status
	 */
	private $type;

	/**
	 * The update / profile message itself
	 */
	private $update;

	/**
	 *  Total number of comments
	 */
	private $commentCount;

	/**
	 *
	 */
	private $iliked;

	private $likedcount;

	private $loadedstatuscount;

	/**
	 * Constructor
	 * @param Registry $registry the registry object
	 * @param int $id ID of the status update / profile message
	 * @return void
	 */
	public function __construct( Registry $registry, $id=0 )
	{
		$this->registry = $registry;
		$this->id = 0;
	}

	/**
	 * user id
	 *
	 * @param int $uid
	 */
	public function Updates($profile)
	{
		$profileType = $profile->getProfileType();

		switch($profileType)
		{
			case 2:{
				$this->listFBStatus($profile);
			}
			break;
			default:{
				$this->listStatusFromLocalDB($profile);
			}
			break;

		}
	}
	
	//Comments
	public function Comments($msgid, $uid, $profileid, $profile, $loadAll)
	{
		$profileType = $profile->getProfileType();

		switch($profileType)
		{
			case 2:
				return $this->getFBComments($msgid, $profile, $loadAll);
			break;
			default:
				return $this->getDBComments($msgid, $uid, $profileid, $loadAll);
			break;
		}
	}
	
	private function getFBComments($msgid, $profile, $loadAll){
		
		$fb_connector = $profile->getInitFBConnector();
		$fbProfileID = $fb_connector->getUserID();
		
		$data = array();
		
		$allComments = $fb_connector->getComments($msgid);

		$this->commentCount = count($allComments);
		
		if( $this->commentCount > 0 )
		{
			foreach ($allComments as $comment)
			{
				$row = array();
				
				$commentID = $comment['post_fbid'];
						
				$fromid = $comment['fromid'];
				$friendinfo = $profile->getFBFriendInfo($fromid);
				
				$row['com_id'] = $commentID;
				$row['photo'] = $friendinfo['pic_small_with_logo'];
				$row['comment'] = $comment['text'];
				$row['created'] = $this->time_stamp($comment['time']);
				$profileURL = "<a href= ".$friendinfo['profile_url']." target=\"_blank\" class=\"viewprofile\">".$friendinfo['name']."</a>";
				$row['name'] = $profileURL;
				$string = 'commentclose'.$commentID;
				if ($fromid == $fbProfileID)
					$row[$string] = "<a class=\"stcommentdelete\" href=\"#\" id='$commentID' title='Delete Comment'>X</a>";
				else
					$row[$string] = "";
				
				$data[] = $row;
			}				
		}
		
		return $data;		
	}

	private function getDBComments($msgid, $uid, $profileid, $loadAll){
	
		$sql = "
				select 	p.user_id, p.name, p.photo, p.profile_name, p.profile_id, p.email, p.gender, p.dob, p.is_default, p.about, 
				c.com_id, c.comment, c.status_id_fk, c.uid_fk, c.created, c.profile_id_fk 
				from  
				profile p ,comments c  
				where p.user_id  = c.uid_fk and p.profile_id = c.profile_id_fk and  c.status_id_fk = '$msgid'     
				order by c.com_id desc";
			
		$this->registry->getObject('db')->executeQuery( $sql );

		$data = array();

		$this->commentCount = $this->registry->getObject('db')->numRows();

		if( $this->registry->getObject('db')->numRows() > 0 )
		{		
			if ($loadAll == false)
			{
				$count = 0;
				while( ($row = $this->registry->getObject('db')->getRows()) && $count < 2)
				{
					$commentID = $row['com_id'];
					$row['created'] = $this->time_stamp($row['created']);
					$row['name'] = ConvertProfileTOURL($row['name'], $row['user_id'], $row['profile_id']);
					$string = 'commentclose'.$commentID;
					if ($row['user_id'] == $uid && $row['profile_id'] == $profileid)
					$row[$string] = "<a class=\"stcommentdelete\" href=\"#\" id='$commentID' title='Delete Comment'>X</a>";
					else
					$row[$string] = "";

					$data[] = $row;
					++$count;
				}
			}
			else
			{
				while( ($row = $this->registry->getObject('db')->getRows()))
				{
					$commentID = $row['com_id'];
					$row['created'] = $this->time_stamp($row['created']);
					$row['name'] = ConvertProfileTOURL($row['name'], $row['user_id'], $row['profile_id']);
					$string = 'commentclose'.$commentID;
					if ($row['user_id'] == $uid && $row['profile_id'] == $profileid)
					$row[$string] = "<a class=\"stcommentdelete\" href=\"#\" id='$commentID' title='Delete Comment'>X</a>";
					else
					$row[$string] = "";
					$data[] = $row;
				}
			}
		}
		return $data;
	}

	private function listStatusFromLocalDB($profile){
				
		$profileid = $profile->getProfileID();
		$uid = $profile->getUserID();

		$wherecls = '';
		if (isset($_SESSION['sn_min_status_id']))
		{
			$minstatusid = $_SESSION['sn_min_status_id'];
			$wherecls = "AND S.status_id < '$minstatusid'";
		}
		else
		{
			$minstatusid = 0;
			$wherecls = " AND S.status_id > '$minstatusid'";
		}

		$sql = "
			select 	S.status_id, S.message, S.posted ,P.profile_name,P.photo, P.name, P.user_id, P.profile_id
			from 	statuses S, users U, profile P 
			where  
			(
				(
					(S.profile_id_fk = P.profile_id AND S.profile_id_fk = '$profileid') AND (S.uid_fk = U.uid AND P.user_id = U.uid AND (P.user_id = '$uid'))
				
				)
				
				OR 
				(
					(S.profile_id_fk = P.profile_id AND S.profile_id_fk  IN ( SELECT r.profileid from relationships r where  (friendid = '$uid' and friendprofileid = $profileid) ) ) 
						AND (S.uid_fk = U.uid AND P.user_id = U.uid AND (P.user_id IN ( SELECT r.userid from relationships r where  (friendid = '$uid' and friendprofileid = $profileid) )))

					OR 
					
					(S.profile_id_fk = P.profile_id AND S.profile_id_fk  IN ( SELECT r.friendprofileid from relationships r where  (userid = '$uid' and profileid = $profileid) ) ) 
						AND (S.uid_fk = U.uid AND P.user_id = U.uid AND (P.user_id IN ( SELECT r.friendid from relationships r where  (userid = '$uid' and profileid = $profileid) )))
				)			 
			 )
			 
			 $wherecls
			 
			ORDER by S.status_id desc ";

			 $this->registry->getObject('db')->executeQuery( $sql );

			 $data = array();

			 $this->loadedstatuscount = $this->registry->getObject('db')->numRows();
			 
			

			 if( $this->registry->getObject('db')->numRows() > 0 )
			 {
			 	$count = 0;
			 	while( ($row = $this->registry->getObject('db')->getRows()) && $count < 10)
			 	{
			 		$row['posted'] = $this->time_stamp($row['posted']);
			 		$row['myphoto'] = $this->registry->getObject('authenticate')->getUser()->getCurrentProfile()->getPhoto();
			 		$row['orimessage'] = $row['message'];
			 		$row['message'] = $this->tolink(htmlentities($row['message']));
			 		$row['name'] = ConvertProfileTOURL($row['name'], $row['user_id'], $row['profile_id']);

			 		$statusID = $row['status_id'];
			 		$string = 'statusdelete'.$statusID;
			 		 
			 		if ($row['user_id'] == $uid && $row['profile_id'] == $profileid)
			 		$row[$string] = "<a class=\"stdelete\" href=\"#\" id='$statusID' title='Delete update'>X</a>";
			 		else
			 		$row[$string] = "";

			 		$data[] = $row;
			 		$minstatusid = $row['status_id'];
			 		++$count;
			 	}
			 }

			 $_SESSION['sn_min_status_id']  = $minstatusid;

			 $cachedata = $this->registry->getObject('db')->cacheData( $data );
			 	
			 $this->registry->getObject('template')->getPage()->addTag( 'status_msgs', array( 'DATA', $cachedata ) );

			 $this->registry->getObject('template')->parseOutput();

			 foreach( $data as $statusmsg)
			 {
			 	$status_id = $statusmsg['status_id'];
			 	$text = $this->LoadLikes($status_id, $uid, $profileid);
			 	$iliked = $this->getILiked();
			 	$likesCount = $this->getLikesCount();
			 	$this->registry->getObject('template')->addTemplateBit( 'WALLLIKE'.$status_id, 'wall/wall_like.tpl.php');
			 	$this->registry->getObject('template')->getPage()->addPPTag('status_id', $status_id);

			 	if ($iliked)
			 	{
			 		$this->registry->getObject('template')->getPage()->addPPTag('likeunlike', 'unlike');
			 		$this->registry->getObject('template')->getPage()->addPPTag('likeval', 0);
			 	}
			 	else
			 	{
			 		$this->registry->getObject('template')->getPage()->addPPTag('likeunlike', 'like');
			 		$this->registry->getObject('template')->getPage()->addPPTag('likeval', 1);
			 	}

			 	$this->registry->getObject('template')->parseOutput();

			 	if ($likesCount == 0)
			 	{
			 		$this->registry->getObject('template')->addTemplateBit( 'WALLSTATUSLIKES'.$status_id, '');
			 	}
			 	else
			 	{
			 		$this->registry->getObject('template')->addTemplateBit( 'WALLSTATUSLIKES'.$status_id, 'wall/wall_likes.tpl.php');
			 		 
			 		 
			 		$this->registry->getObject('template')->getPage()->addPPTag('text', $text);
			 		$this->registry->getObject('template')->getPage()->addPPTag('likescount', $likesCount);
			 	}
			 	$this->registry->getObject('template')->parseOutput();

			 	$comments = $this->Comments($status_id, $uid, $profileid, $profile, false);
			 	
			 	if ($comments)
			 	{
			 		if ($this->getCommentCount() > 2)
			 		{
			 			$this->registry->getObject('template')->addTemplateBit( 'WALLREADMORE'.$status_id, 'wall/wall_readmore.tpl.php');
			 			$this->registry->getObject('template')->getPage()->addPPTag('remainingcomments', $this->getCommentCount());

			 			$this->registry->getObject('template')->addTemplateBit( 'WALLCOMMENT'.$status_id, 'wall/wallcomments_two.tpl.php');

			 		}
			 		else
			 		{
			 			$this->registry->getObject('template')->addTemplateBit( 'WALLREADMORE'.$status_id, '');
			 			$this->registry->getObject('template')->addTemplateBit( 'WALLCOMMENT'.$status_id, 'wall/wallcomments.tpl.php');
			 		}

			 		$this->registry->getObject('template')->getPage()->addPPTag('status_id', $status_id);
			 		$cachedata = $this->registry->getObject('db')->cacheData( $comments );
			 		$this->registry->getObject('template')->getPage()->addPPTag( 'wallcomments'.$status_id, array( 'DATA', $cachedata ));
			 		$this->registry->getObject('template')->parseOutput();
			 	}
			 	else
			 	{
			 		$this->registry->getObject('template')->addTemplateBit( 'WALLCOMMENT'.$status_id, '');
			 		$this->registry->getObject('template')->addTemplateBit( 'WALLREADMORE'.$status_id, '');
			 	}
			 }
	}

	public function listFBStatus($profile){

		$profileid = $profile->getProfileID();
		$uid = $profile->getUserID();

		$fb_connector = $profile->getInitFBConnector();
		
		
		$minstatusid = '';
		$limit = '20';
		if (isset($_SESSION['sn_min_status_id']))
		{
			$minstatusid = $_SESSION['sn_min_status_id'];
			$limit = '20';
		}
		
		$fbProfileID = $fb_connector->getUserID();
		$statuses = $fb_connector->getMyFeeds($limit, $minstatusid);
		
		$this->loadedstatuscount = count($statuses);

		$data = array();
		
		foreach ($statuses as $status){
			$row = array();
				
			$friendid = $status['actor_id'];
			$friendinfo = $profile->getFBFriendInfo($friendid);;
			$removeHtml = false;

			$message = $status['message'].'</br>';
			if (isset($status['attachment'])){
				$attachment = $status['attachment'];
				if (isset($attachment['media'])){
					$removeHtml = false;
					$medias = $attachment['media'];
					foreach ($medias as $media){
						$type = $media['type'];
						if ($type == 'photo'){
							$message.='<img src="'.$media['src'].'">';
						}
						else if ($type == 'link'){
							$message.=$media['src'];
							$removeHtml = true;
						}
					}
				}
			}

			$row['status_id'] = $status['post_id'];
			$row['message'] = $message;
			$row['profile_name'] = $friendinfo['name'];
			$row['photo'] = $friendinfo['pic_small_with_logo'];
			$row['name'] = $friendinfo['name'];
			$row['user_id'] = $friendid;
			$row['profile_id'] = $friendid;

			$row['posted'] = $this->time_stamp($status['created_time']);
			$row['myphoto'] = $this->registry->getObject('authenticate')->getUser()->getCurrentProfile()->getPhoto();
				
			if ($removeHtml == true)
			$row['orimessage'] = $row['message'];
			else
			$row['orimessage'] = '';

			$profileURL = "<a href= ".$friendinfo['profile_url']." class=\"viewprofile\">".$row['name']."</a>";
			$row['name'] = $profileURL;

			$statusID = $row['status_id'];
			$string = 'statusdelete'.$statusID;

			if ($row['user_id'] == $fbProfileID)
			{
				$row[$string] = "<a class=\"stdelete\" href=\"#\" id='$statusID' title='Delete update'>X</a>";
			}
			else
			{
				$row[$string] = "";
			}

			$data[] = $row;
			$minstatusid = $status['created_time'];
		}
			
		$_SESSION['sn_min_status_id']  = $minstatusid;

		$cachedata = $this->registry->getObject('db')->cacheData( $data );

		$this->registry->getObject('template')->getPage()->addTag( 'status_msgs', array( 'DATA', $cachedata ) );

		$this->registry->getObject('template')->parseOutput();

		foreach( $statuses as $statusmsg){
				
			$status_id = $statusmsg['post_id'];
			$likes = $statusmsg['likes'];
			if (isset($likes['user_likes']))
			$iliked = $likes['user_likes'];
			else
			$iliked = 0;
			$canLike = $likes['can_like'];
				
			if (isset($likes['count']))
			$likesCount = $likes['count'];
			else
			$likesCount = 0;
				
			if($iliked)
			$text = "You and $likesCount friend like this";
			else
			$text = "$likesCount like this";
				
			$this->registry->getObject('template')->addTemplateBit( 'WALLLIKE'.$status_id, 'wall/wall_like.tpl.php');
			$this->registry->getObject('template')->getPage()->addPPTag('status_id', $status_id);

			if ($canLike)
			{
				if ($iliked)
				{
					$this->registry->getObject('template')->getPage()->addPPTag('likeunlike', 'unlike');
					$this->registry->getObject('template')->getPage()->addPPTag('likeval', 0);
				}
				else
				{
					$this->registry->getObject('template')->getPage()->addPPTag('likeunlike', 'like');
					$this->registry->getObject('template')->getPage()->addPPTag('likeval', 1);
				}
			}

			$this->registry->getObject('template')->parseOutput();

			if ($likesCount == 0)
			{
				$this->registry->getObject('template')->addTemplateBit( 'WALLSTATUSLIKES'.$status_id, '');
			}
			else
			{
				$this->registry->getObject('template')->addTemplateBit( 'WALLSTATUSLIKES'.$status_id, 'wall/wall_likes.tpl.php');


				$this->registry->getObject('template')->getPage()->addPPTag('text', $text);
				$this->registry->getObject('template')->getPage()->addPPTag('likescount', $likesCount);
			}
			$this->registry->getObject('template')->parseOutput();

			$statComment = $statusmsg['comments'];
			$commentCount = $statComment['count'];
			$commentList = $statComment['comment_list'];
				
			$hiddenComments = $commentCount - count($commentList);
				
			$comments = array();
			if ($commentCount > 0)
			{
				foreach ($commentList as $fbComment){
					$fromid = $fbComment['fromid'];
					$friendinfo = $profile->getFBFriendInfo($fromid);
					$comment = array();
						
					$comment['com_id'] = $fbComment['id'];
					$commentID = $comment['com_id'];
					$comment['photo'] = $friendinfo['pic_small_with_logo'];
					$profileURL = "<a href= ".$friendinfo['profile_url']." target=\"_blank\" class=\"viewprofile\">".$friendinfo['name']."</a>";
					$comment['name'] = $profileURL;
					$comment['comment'] = $fbComment['text'];
					$comment['created'] = $this->time_stamp($fbComment['time']);
						
					$string = 'commentclose'.$fbComment['id'];
					if ($fromid == $fbProfileID)
					$comment[$string] = "<a class=\"stcommentdelete\" href=\"#\" id='$commentID' title='Delete Comment'>X</a>";
					else
					$comment[$string] = "";
						
					$comments[] = $comment;
				}

				if ($hiddenComments > 0)
				{
					$this->registry->getObject('template')->addTemplateBit( 'WALLREADMORE'.$status_id, 'wall/wall_readmore.tpl.php');
					$this->registry->getObject('template')->getPage()->addPPTag('remainingcomments', $commentCount);

					$this->registry->getObject('template')->addTemplateBit( 'WALLCOMMENT'.$status_id, 'wall/wallcomments_two.tpl.php');

				}
				else
				{
					$this->registry->getObject('template')->addTemplateBit( 'WALLREADMORE'.$status_id, '');
					$this->registry->getObject('template')->addTemplateBit( 'WALLCOMMENT'.$status_id, 'wall/wallcomments.tpl.php');
				}

				$this->registry->getObject('template')->getPage()->addPPTag('status_id', $status_id);
				$cachedata = $this->registry->getObject('db')->cacheData( $comments );
				$this->registry->getObject('template')->getPage()->addPPTag( 'wallcomments'.$status_id, array( 'DATA', $cachedata ));
				$this->registry->getObject('template')->parseOutput();
			}
			else
			{
				$this->registry->getObject('template')->addTemplateBit( 'WALLCOMMENT'.$status_id, '');
				$this->registry->getObject('template')->addTemplateBit( 'WALLREADMORE'.$status_id, '');
			}
		}
	}

	//Avatar Image
	public function Gravatar($uid)
	{
		$query = mysql_query("SELECT email FROM `users` WHERE uid='$uid'") or die(mysql_error());
		$row = mysql_fetch_array($query);
		if(!empty($row))
		{
			$email=$row['email'];
			$lowercase = strtolower($email);
			$imagecode = md5( $lowercase );
			$data="http://www.gravatar.com/avatar.php?gravatar_id=$imagecode";
			return $data;
		}
		else
		{
		 $data="default.jpg";
		 return $data;
		}
	}

	//Insert Update
	public function InsertUpdate($uid, $profile, $update)
	{
		$profileType = $profile->getProfileType();

		switch($profileType)
		{
			case 2:
				return $this->InsertFBUpdate($uid, $profile, $update);
				break;
			default:
				return $this->InsertDBUpdate($uid, $profile, $update);
				break;
		}
	}

	private function InsertDBUpdate($uid, $profile, $update){
		$profileid = $profile->getProfileID();
		$time = time();

		$data = array();
		$data['message'] = $update;
		$data['type'] = 1;
		$data['uid_fk'] = $uid;
		$data['profile_id_fk'] = $profileid;
		$data['posted'] = $time;

		$this->registry->getObject('db')->insertRecords('statuses', $data);

		$sql = "
			select 	S.status_id, S.message, S.posted ,P.profile_name, P.photo , P.name 
			from 	statuses S, profile P 
			where  (S.profile_id_fk = P.profile_id AND S.profile_id_fk = '$profileid')  
			AND (S.uid_fk = P.user_id AND (P.user_id = '$uid')) 
			ORDER by S.status_id desc limit 1 ";

		$data = array();
		$this->registry->getObject('db')->executeQuery( $sql );

		if( $this->registry->getObject('db')->numRows() > 0 )
		{
			//$this->empty = false;
			// iterate through the statuses, adding the ID to the IDs array, making the time friendly, and saving the stream
			while( $row = $this->registry->getObject('db')->getRows() )
			{
				$row['posted'] = $this->time_stamp($row['posted']);
				$row['orimessage'] = $row['message'];
				$row['message'] = $this->tolink(htmlentities($row['message']));
				$row['name'] = ConvertProfileTOURL($row['name'], $uid, $profileid);
				$row['myphoto'] = $this->registry->getObject('authenticate')->getUser()->getCurrentProfile()->getPhoto();
				$statusID = $row['status_id'];
				$string = 'statusdelete'.$statusID;
				$row[$string] = "<a class=\"stdelete\" href=\"#\" id='$statusID' title='Delete update'>X</a>";
				$data[] = $row;

				$this->registry->getObject('template')->addTemplateBit( 'WALLLIKE'.$row['status_id'], 'wall/wall_like.tpl.php');
				$this->registry->getObject('template')->getPage()->addPPTag('status_id', $row['status_id']);
				$this->registry->getObject('template')->getPage()->addPPTag('likeunlike', 'like');
				$this->registry->getObject('template')->getPage()->addPPTag('likeval', 1);

				$this->registry->getObject('template')->addTemplateBit( 'WALLCOMMENT'.$row['status_id'], '');
				$this->registry->getObject('template')->addTemplateBit( 'WALLSTATUSLIKES'.$row['status_id'], '');
				$this->registry->getObject('template')->addTemplateBit( 'WALLREADMORE'.$row['status_id'], '');
			}
		}

		return $data;
	}

	private function InsertFBUpdate($uid, $profile, $update){

		$privacy = array(
           'description' => 'Custom privacy',
            'value'   => 'CUSTOM',
			'friends' => 'ALL_FRIENDS',
		);

		$fb_connector = $profile->getInitFBConnector(false);

		$fbProfileID = $fb_connector->getUserID();
		$appLink = $this->registry->getSetting('siteurl');
		$appName = $this->registry->getSetting('sitename');

		$result = $fb_connector->uploadURL($fbProfileID, '','',
		$update, '', '', $appName, $appLink, $privacy, '', true);
		$statusID = $result['id'];
		$statmsg = $fb_connector->getPost($statusID);
		$status = $statmsg[0]['fql_result_set'][0];
		$friendinfo = $statmsg[1]['fql_result_set'][0];

		$removeHtml = true;

		$message = $status['message'].'</br>';
		if (isset($status['attachment'])){
			$attachment = $status['attachment'];
			if (isset($attachment['media'])){
				$removeHtml = false;
				$medias = $attachment['media'];
				foreach ($medias as $media){
					$type = $media['type'];
					if ($type == 'photo'){
						$message.='<img src="'.$media['src'].'">';
					}
					else if ($type == 'link'){
						$message.=$media['src'];
						$removeHtml = true;
					}
				}
			}
		}

		$row = array();
		$data = array();

		$row['status_id'] = $status['post_id'];
		$row['message'] = $message;
		$row['posted'] = $status['created_time'];
		$row['profile_name'] = $friendinfo['name'];
		$row['photo'] = $friendinfo['pic_small'];
		$row['user_id'] = $fbProfileID;
		$row['profile_id'] = $fbProfileID;

		$row['posted'] = $this->time_stamp($row['posted']);
		$row['myphoto'] = $friendinfo['pic_small'];
			
		if ($removeHtml == true)
		$row['orimessage'] = $row['message'];
		else
		$row['orimessage'] = '';

		$profileURL = "<a href= ".$friendinfo['url']." class=\"viewprofile\">".$friendinfo['name']."</a>";
		$row['name'] = $profileURL;

		$string = 'statusdelete'.$statusID;
		$row[$string] = "<a class=\"stdelete\" href=\"#\" id='$statusID' title='Delete update'>X</a>";

		$data[] = $row;

		$this->registry->getObject('template')->addTemplateBit( 'WALLLIKE'.$row['status_id'], 'wall/wall_like.tpl.php');
		$this->registry->getObject('template')->getPage()->addPPTag('status_id', $row['status_id']);
		$this->registry->getObject('template')->getPage()->addPPTag('likeunlike', 'like');
		$this->registry->getObject('template')->getPage()->addPPTag('likeval', 1);

		$this->registry->getObject('template')->addTemplateBit( 'WALLCOMMENT'.$row['status_id'], '');
		$this->registry->getObject('template')->addTemplateBit( 'WALLSTATUSLIKES'.$row['status_id'], '');
		$this->registry->getObject('template')->addTemplateBit( 'WALLREADMORE'.$row['status_id'], '');

		return $data;
	}

	public function LoadLikes($status_id, $userid, $profileid)
	{
		$sql = "SELECT * from ikes where status_id_fk = '$status_id' ";
		$this->registry->getObject('db')->executeQuery( $sql );
		$totallikes = $this->registry->getObject('db')->numRows();
		$this->likedcount = $totallikes;

		$sql = "SELECT * from ikes where status_id_fk = '$status_id' AND (user_id_fk = '$userid' AND profile_id_fk = '$profileid')";
		$this->registry->getObject('db')->executeQuery( $sql );
		$this->iliked = false;
		if ($this->registry->getObject('db')->numRows() >= 1)
		$this->iliked = true;
		$text = "";
		if ($this->iliked)
		{
			$totallikes-=1;
			if ($totallikes > 0)
			{
				if ($totallikes == 1)
				$text = "You and $totallikes friend like this";
				else
				$text = "You and $totallikes friends like this";
			}
			else
			$text = "You like this";
		}
		else
		{
			if ($totallikes > 1)
			$text = "$totallikes friends like this";
			else
			$text = "$totallikes friend like this";


		}
		return $text;
	}

	public function InsertLike($status_id, $userid, $profileid)
	{
		$time = time();

		$data = array();
		$data['type'] = 'likes';
		$data['status_id_fk'] = $status_id;
		$data['user_id_fk'] = $userid;
		$data['profile_id_fk'] = $profileid;
		$data['iked'] = $time;

		$sql = "SELECT * from ikes where status_id_fk = '$status_id' AND (user_id_fk = '$userid' AND profile_id_fk = '$profileid')";
		$this->registry->getObject('db')->executeQuery( $sql );
		$this->iliked = false;
		if ($this->registry->getObject('db')->numRows() == 0)
		$this->registry->getObject('db')->insertRecords('ikes', $data);

		return $this->LoadLikes($status_id, $userid, $profileid);
	}

	public function DeleteLike($status_id, $userid, $profileid)
	{
		$this->registry->getObject('db')->deleteRecords('ikes', 'status_id_fk = '.$status_id.' AND (user_id_fk = '.$userid.' AND profile_id_fk = '.$profileid.')', 1);
		return $this->LoadLikes($status_id, $userid, $profileid);
	}

	//Delete update
	public function DeleteUpdate($msg_id, $profile)
	{
		$profileType = $profile->getProfileType();

		switch($profileType)
		{
			case 2:
				return $this->DeleteFBUpdate($msg_id, $profile);
				break;
			default:
				return $this->DeleteDBUpdate($msg_id);
				break;
		}		
	}
	
	private function DeleteDBUpdate($msg_id){

		$this->registry->getObject('db')->deleteRecords( 'ikes', 'status_id_fk = '.$msg_id, 1);
		$this->registry->getObject('db')->deleteRecords( 'comments', 'status_id_fk = '.$msg_id, 1);
		$this->registry->getObject('db')->deleteRecords('statuses', 'status_id='.$msg_id, 1);

		return true;		
	}
	
	private function DeleteFBUpdate($msg_id, $profile){
		$fb_connector = $profile->getInitFBConnector(false);		
		return $fb_connector->delete($msg_id);
	}

	//Insert Comments
	public function InsertComment($commentuid, $commentprofileid, $statusid, $comment, $profile){

		$profileType = $profile->getProfileType();

		switch($profileType)
		{
			case 2:
				return $this->InsertFBComment($statusid, $comment, $profile);
				break;
			default:
				return $this->InsertDBComment($commentuid, $commentprofileid, $statusid, $comment);
				break;
		}
	}


	private function InsertDBComment($commentuid, $commentprofileid, $statusid, $comment){
		$time = time();

		$data = array();
		$data['comment'] = $comment;
		$data['status_id_fk'] = $statusid;
		$data['uid_fk'] = $commentuid;
		$data['profile_id_fk'] = $commentprofileid;
		$data['created'] = $time;

		$this->registry->getObject('db')->insertRecords('comments', $data);

		$sql = "
			SELECT (C.com_id), C.comment, C.created  
			FROM comments C  
			WHERE  (C.status_id_fk = '$statusid')   
			order by C.com_id desc limit 1 ";

		$this->registry->getObject('db')->executeQuery( $sql );

		$data = array();

		$commentedprofile = $this->registry->getObject('authenticate')->getUser()->getCurrentProfile();

		if( $this->registry->getObject('db')->numRows() > 0 )
		{
			//$this->empty = false;
			// iterate through the statuses, adding the ID to the IDs array, making the time friendly, and saving the stream
			while( $row = $this->registry->getObject('db')->getRows() )
			{
				$row['created'] = $this->time_stamp($row['created']);
				$row['name'] =  ConvertProfileTOURL($commentedprofile->getName(), $commentuid, $commentprofileid);
				$row['photo'] =  $commentedprofile->getPhoto();
				$row['comment'] = $this->tolink(htmlentities($row['comment']));
				$commentID = $row['com_id'];
				$string = 'commentclose'.$commentID;
				$row[$string] = "<a class=\"stcommentdelete\" href=\"#\" id='$commentID' title='Delete Comment'>X</a>";
				$data[] = $row;
			}		
		}

		return $data;
	}

	private function InsertFBComment($statusid, $comment, $profile){

		$fb_connector = $profile->getInitFBConnector(false);
		$fbProfileID = $fb_connector->getUserID();
		$userInfo = $profile->getFBFriendInfo($fbProfileID);

		$commentResponse = $fb_connector->postComment($statusid, $comment);
		$commentID = $commentResponse['id'];

		$data = array();
		$row = array();

		$profileURL = "<a href= ".$userInfo['profile_url']." class=\"viewprofile\">".$userInfo['name']."</a>";

		$row['created'] = $this->time_stamp(time());
		$row['name'] =  $profileURL;
		$row['photo'] =  $userInfo['pic_small_with_logo'];
		$row['comment'] = $this->tolink(htmlentities($comment));
		$row['com_id'] = $commentID;
		$string = 'commentclose'.$commentID;

		$row[$string] = "<a class=\"stcommentdelete\" href=\"#\" id='$commentID' title='Delete Comment'>X</a>";

		$data[] = $row;

		return $data;
	}

	//Delete Comments
	public function DeleteComment($com_id, $profile)
	{
		$profileType = $profile->getProfileType();

		switch($profileType)
		{
			case 2:				
				return $this->DeleteFBComment($com_id, $profile);
				break;
			default:
				return $this->DeleteDBComment($com_id);
				break;
		}
	}

	private function DeleteDBComment($com_id){
		$this->registry->getObject('db')->deleteRecords('comments', 'com_id='.$com_id, 1);
		return true;
	}

	private function DeleteFBComment($com_id, $profile){
		$fb_connector = $profile->getInitFBConnector(false);		
		return $fb_connector->delete($com_id);
	}

	function time_stamp($session_time)
	{
		$time_difference = time() - $session_time ;
		$seconds = $time_difference ;
		$minutes = round($time_difference / 60 );
		$hours = round($time_difference / 3600 );
		$days = round($time_difference / 86400 );
		$weeks = round($time_difference / 604800 );
		$months = round($time_difference / 2419200 );
		$years = round($time_difference / 29030400 );

		if($seconds <= 60)
		{
			return "$seconds seconds ago";
		}
		else if($minutes <=60)
		{
			if($minutes==1)
			{
				return "one minute ago";
			}
			else
			{
				return "$minutes minutes ago";
			}
		}
		else if($hours <=24)
		{
			if($hours==1)
			{
				return  "one hour ago";
			}
			else
			{
				return  "$hours hours ago";
			}
		}
		else if($days <=7)
		{
			if($days==1)
			{
				return "one day ago";
			}
			else
			{
				return  "$days days ago";
			}
		}
		else if($weeks <=4)
		{
			if($weeks==1)
			{
				return  "one week ago";
			}
			else
			{
				return  "$weeks weeks ago";
			}
		}
		else if($months <=12)
		{
			if($months==1)
			{
				return  "one month ago";
			}
			else
			{
				return  "$months months ago";
			}
		}
		else
		{
			if($years==1)
			{
				return  "one year ago";
			}
			else
			{
				return "$years years ago";
			}

		}
	}

	function getLoadedStatusCount()
	{
		return $this->loadedstatuscount;
	}

	function getCommentCount()
	{
		return $this->commentCount;
	}

	function getILiked()
	{
		return $this->iliked;
	}

	function getLikesCount()
	{
		return $this->likedcount;
	}

	function tolink($text){
		$text = html_entity_decode($text);
		$text = " ".$text;
		$text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
                '<a href="\\1">\\1</a>', $text);
		$text = eregi_replace('(((f|ht){1}tps://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
                '<a href="\\1">\\1</a>', $text);
		$text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
        '\\1<a href="http://\\2">\\2</a>', $text);
		$text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})',
        '<a href="mailto:\\1">\\1</a>', $text);
		return $text;
	}
}

?>
